// 该文件用于创建路由实例对象，是路由的主配置文件
import { createRouter, createWebHashHistory } from "vue-router";

import store from "@/store";

import staticRoutes from "./routes-static.js";
import asyncRoutes from "./routes-async.js";

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...staticRoutes, ...asyncRoutes],
});

/**
 * 将 staticRoutes 里面所有的 name 给映射出来
 */
function mapStaticRouteNames(routes, result = []) {
  result.push(
    ...routes.filter((route) => route.name).map((route) => route.name)
  );

  routes.forEach((route) => {
    if (route.children) {
      mapStaticRouteNames(route.children, result);
    }
  });

  return result;
}

// 白名单路由
const whiteRoute = ["login", "exception_403", "exception_404"];

// 全局前置守卫
router.beforeEach((to, from) => {
  if (!mapStaticRouteNames(staticRoutes).includes(to.name)) {
    // 当前要去的路由需要登录状态

    // 判断是否有登录状态
    const token = store.getters["app/token"];
    if (!token) {
      // 没有登录，直接跳转到登录页
      return "/login";
    }

    // 判断当前要去的路由是否有访问权限
    if (
      store.getters["app/role"] === 1 &&
      !store.getters["app/permissions"].includes(to.name)
    ) {
      // 没有权限，跳转到 /403
      return { name: "exception_403" };
    }
  }
});

// 导出 router
export default router;
